from flask import Flask, request, jsonify, Blueprint
from models import db, Course, Class, Student, Enrollment, Grade

api = Blueprint('api', __name__)


# 课程管理
@api.route('/courses', methods=['GET'])
def get_courses():
    courses = Course.query.all()
    return jsonify([{
        'course_id': c.course_id, 
        'course_name': c.course_name, 
        'credits': c.credits, 
        'hours': c.hours
    } for c in courses])

@api.route('/courses', methods=['POST'])
def create_course():
    data = request.json
    new_course = Course(course_name=data['course_name'], credits=data['credits'], hours=data['hours'])
    db.session.add(new_course)
    db.session.commit()
    return jsonify({'message': 'Course created'})

# 班次管理
@api.route('/classes', methods=['GET'])
def get_classes():
    classes = Class.query.all()
    return jsonify([{
        'class_id': c.class_id, 
        'class_name': c.class_name, 
        'semester': c.semester, 
        'location': c.location,
        'course_id': c.course_id,
        'students': [{'student_id': s.student_id, 'student_name': s.student_name} for s in c.students]
    } for c in classes])

@api.route('/classes', methods=['POST'])
def create_class():
    data = request.json
    new_class = Class(class_name=data['class_name'], semester=data['semester'], location=data['location'], course_id=data['course_id'])
    db.session.add(new_class)
    db.session.commit()
    return jsonify({'message': 'Class created'})

@api.route('/classes/<int:class_id>/students', methods=['POST'])
def add_student_to_class(class_id):
    data = request.json
    student_id = data['student_id']
    student = Student.query.get(student_id)
    if student:
        _class = Class.query.get(class_id)
        if _class:
            _class.students.append(student)
            db.session.commit()
            return jsonify({'message': 'Student added to class'})
    return jsonify({'message': 'Student or Class not found'}), 404
